import React from 'react';
import _ from 'underscore';
import moment from 'moment';

import {Scope} from 'lib/scopeFactory';
import TimeStore from 'lib/stores/time-store';
import format from 'lib/util/format';

import basicInfo from '../apis/basicInfo';
import {parseToGrid} from '../apis/tracelist';
import {propConfig, coreApi, parseToChart} from '../apis/core-util';

export default class SingleScope extends Scope {
  constructor(props, context) {
    super(props, context);

    this.domainId = props.routeParams.domainId;
    this.urlId = props.routeParams.urlId;

    this.$state = {
      title:'',
      requestTime:null,
      chart0:{
        loading:true
      }
      ,chart1:{
        loading:true
      }
      ,chart2:{
        loading:true
      },
      errorRequestOffset:0,
      errorRequest:{
        loading:true
      },
      slowlyRequestOffset:0,
      slowlyRequest:{
        loading:true
      }
    }; // $state

    this.basicInfoApi = basicInfo({
      id:()=>this.urlId ? this.urlId : this.domainId,
      parentId:()=>this.urlId ? this.domainId : undefined,
      urlName:'url'
    });

    this.chart0Api = coreApi({
      size:30,
      limit:5,
      domainId:()=>this.domainId,
      urlId:()=>this.urlId,
      classify:'url',
      urlName:'ajax/ajaxdata',
      viewKey:'avg_resp_ajax',
      order:propConfig['avg_resp_ajax'].order
    },TimeStore.getValue);

    this.chart1Api = coreApi({
      size:30,
      limit:5,
      domainId:()=>this.domainId,
      urlId:()=>this.urlId,
      classify:'url',
      urlName:'ajax/ajaxdata',
      viewKey:'count_resp_ajax',
      order:propConfig['count_resp_ajax'].order
    },TimeStore.getValue);

    this.chart2Api = coreApi({
      size:30,
      limit:5,
      domainId:()=>this.domainId,
      urlId:()=>this.urlId,
      classify:'url',
      urlName:'ajax/ajaxerrordata',
      viewKey:'error_rate',
      order:propConfig['error_rate'].order
    },TimeStore.getValue);

    this.errorRequestApi = coreApi({
      size:1,
      limit:10,
      traceType:1,
      order:301,
      domainId:this.domainId,
      urlId:this.urlId,
      offset:()=>this.$state.errorRequestOffset,
      urlName:'ajax/ajaxtracelist'
    },TimeStore.getValue);

    this.slowlyRequestApi = coreApi({
      size:1,
      limit:10,
      traceType:2,
      order:301,
      domainId:this.domainId,
      urlId:this.urlId,
      offset:()=>this.$state.slowlyRequestOffset,
      urlName:'ajax/ajaxtracelist'
    },TimeStore.getValue);

    this.$state.requestColumns = [
      {
        title:'域名',
        key:'domain'
      },
      {
        title:'请求名称',
        key:'url',
        render:(url,rowData)=>(<a href={`#/domain/${this.domainId}/url/${rowData.urlId}/${rowData.traceType}/${this.requestTime}`}>{url}</a>)
      },
      {
        title:'平均耗时',
        key:'avg',
        sortable:true,
        formatter:format.numSecs
      },
      {
        title:'采集次数',
        key:'count',
        sortable:true,
        format:format.integer
      },
      {
        title:'影响用户数',
        key:'affected',
        sortable:true,
        format:format.integer
      },
      {
        title:'最近采集时间',
        key:'lastTime',
        formatter: (item) => {
          return moment(item).format('YYYY/MM/DD HH:mm')
        }
      }
    ]
  } // constructor

  fetchBasicInfo() {
    this.basicInfoApi
        .fetch()
        .fail(()=>this.$state.title = '')
        .done((data,params)=>this.$state.title = data.result[0].name)
        .always(()=>this.emit());
  } // fetchBasicInfo

  fetchChart0() {
    this.chart0Api
        .fetch()
        .progress(()=>{
          this.$state.chart0 = {
            loading:true
          };
          this.emit();
        })
        .fail((error,params)=>{
          this.$state.chart0 = {
            error
          };
        })
        .done((data,params)=>{
          this.$state.chart0 = {
            data: parseToChart(data,params)
          };
        })
        .always(()=>{
          this.emit()
        });
  } // fetchChart0

  fetchChart1() {
    this.chart1Api
        .fetch()
        .progress(()=>{
          this.$state.chart1 = {
            loading:true
          };
          this.emit();
        })
        .fail((error,params)=>{
          this.$state.chart1 = {
            error
          };
        })
        .done((data,params)=>{
          this.$state.chart1 = {
            data: parseToChart(data,params)
          };
        })
        .always(()=>{
          this.emit()
        });
  } // fetchChart1

  fetchChart2() {
    this.chart2Api
        .fetch()
        .progress(()=>{
          this.$state.chart2 = {
            loading:true
          };
          this.emit();
        })
        .fail((error,params)=>{
          this.$state.chart2 = {
            error
          };
        })
        .done((data,params)=>{
          this.$state.chart2 = {
            data: parseToChart(data,params)
          };
        })
        .always(()=>{
          this.emit()
        });
  } // fetchChart2

  fetchErrorRequest() {
    this.errorRequestApi
        .fetch()
        .progress(()=>{
          this.requestTime = Date.now();
          this.$state.errorRequest = {
            loading:true
          };
          this.emit();
        })
        .fail((error,params)=>{
          this.$state.errorRequest = {
            error
          };
        })
        .done((data, params)=>{
          this.$state.errorRequest = parseToGrid(_.map(data.ajaxTraceListResults, item=>{
            item.traceType = 'error';
            return item;
          }), params);
        })
        .always(()=>{
          this.emit();
        });
  } // fetchErrorRequest

  fetchSlowlyRequest() {
    this.slowlyRequestApi
        .fetch()
        .progress(()=>{
          this.$state.slowlyRequest = {
            loading:true
          };
          this.emit();
        })
        .fail((error,params)=>{
          this.$state.slowlyRequest = {
            error
          };
        })
        .done((data,params)=>{
          this.$state.slowlyRequest = parseToGrid(_.map(data.ajaxTraceListResults,item=>{
            item.traceType = 'slow';
            return item;
          }), params);
        })
        .always(()=>{
          this.emit();
        });
  } // fetchErrorRequest


  fetch() {
    this.fetchBasicInfo();
    this.fetchChart0();
    this.fetchChart1();
    this.fetchChart2();
    this.fetchErrorRequest();
    this.fetchSlowlyRequest();
  }

  $settime() {
    this.fetch();
  }

  $load() {
    this.fetch();
  }
}
